package com.clouddot.baipai.ui.fragment.H_MainFragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.constraint.ConstraintLayout;
import android.text.Html;
import android.text.Spanned;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.VideoView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.clouddot.baipai.R;
import com.clouddot.baipai.infrastructure.environment.Env;
import com.clouddot.baipai.model.beam.getArcticList.getArcticListResponse;
import com.clouddot.baipai.model.beam.getClassInfoById.getClassInfoByIdResponse;
import com.clouddot.baipai.model.beam.getClassInfoList.classInfoItem;
import com.clouddot.baipai.model.beam.getClassInfoList.getClassInfoListResponse;
import com.clouddot.baipai.model.beam.getCurrentCourse.getCurrentCourseResponse;
import com.clouddot.baipai.model.beam.getSchoolInfo.getSchoolInfoResponse;
import com.clouddot.baipai.ui.fragment.BaseFragment;
import com.clouddot.baipai.ui.dialog.H_Dialog.H_ImageDailog;
import com.clouddot.baipai.ui.util.EscapeUnescapeUtil;
import com.clouddot.baipai.ui.util.ThreadPool.ThreadPool;
import com.clouddot.baipai.ui.util.ToastUtil;
import com.danikula.videocache.HttpProxyCacheServer;
import com.danikula.videocache.file.FileNameGenerator;

import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by wxy on 2018/4/10.
 */

public class H_HomeFragment extends BaseFragment {

    private View view;
    private ImageView photo;
    private Context context;

    private H_ImageDailog H_ImageDailog;
    private ImageView close;
    private ImageView left,right;
    private TextView title,time,content;
    private TextView courseName,teacherName,currentTime;
    private ImageView image;
    private LinearLayout linearLayout;
    private List<String> strings = new ArrayList<>();
    private List<classInfoItem> list = new ArrayList<classInfoItem>();

    private int count = 0;
    private int currentImageItem = 0;
    private Thread thread4Data;
    private boolean isFragment;
    private getCurrentCourseThread getCurrentCourseThread;
    private AutoPlayImageThread autoPlayImageThread;

    private ImageView closeVideo ;
    private VideoView videoView;
    private ConstraintLayout videoViewP;
    private ImageView play;

    private HttpProxyCacheServer proxy;
    private List<String> videoPath  = new ArrayList<>();

    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getCurrentCourseThread = new getCurrentCourseThread();
        getCurrentCourseThread.start();
    }
    public HttpProxyCacheServer getProxy() {
        return proxy == null ? (proxy = newProxy()) : proxy;
    }

    private HttpProxyCacheServer newProxy() {
        return  new HttpProxyCacheServer.Builder(getActivity())
                .maxCacheSize(1024 * 1024 * 1024)
                .fileNameGenerator(new H_HomeFragment.MyFileNameGenerator())
                .build();
    }

    public class MyFileNameGenerator implements FileNameGenerator {
        public String generate(String url) {
            return "/BanPai" + videoPath.get(0);
        }
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        return view;
    }

    @Override
    protected void setContentView() {
        super.setContentView();

        view = LayoutInflater.from(context).inflate(R.layout.h_f_homefg,null);
    }

    @Override
    protected void initControls() {
        super.initControls();
        photo = view.findViewById(R.id.photo);
        linearLayout = view.findViewById(R.id.content2);
        title = view.findViewById(R.id.title);
        time = view.findViewById(R.id.time);
        content = view.findViewById(R.id.content);
        left = view.findViewById(R.id.left);
        right = view.findViewById(R.id.right);
        courseName = view.findViewById(R.id.courseName);
        teacherName = view.findViewById(R.id.teacherName);
        currentTime = view.findViewById(R.id.currentTime);
        image = view.findViewById(R.id.image);
        play = view.findViewById(R.id.play);
        closeVideo = getActivity().findViewById(R.id.close);
        videoView = getActivity().findViewById(R.id.videoView);
        videoViewP = getActivity().findViewById(R.id.videoViewP);
    }

    @Override
    protected void setListener() {
        super.setListener();
        linearLayout.setOnClickListener(photoListener);
        left.setOnClickListener(leftListener);
        right.setOnClickListener(rightListener);
        play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String url = Env.getAppContext().IP + videoPath.get(0);
                String proxyUrl = getProxy().getProxyUrl(url);
                videoView.setVideoPath(proxyUrl);
                videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mp) {
                        videoView.start();
                    }
                });
                videoView.requestFocus();
                videoView.start();
                videoViewP.setVisibility(View.VISIBLE);

            }
        });

        closeVideo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                videoViewP.setVisibility(View.GONE);
            }
        });
    }

    @Override
    protected void loadParams() {
        super.loadParams();
    }

    @Override
    public void onAttach(Context context) {
        this.context = context;
        super.onAttach(context);
    }


    @Override
    public void onPause() {
        super.onPause();
        isFragment = true;
        if(getCurrentCourseThread != null) getCurrentCourseThread.stopRun();
        if(autoPlayImageThread != null) autoPlayImageThread.stopRun();
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
    }


    @Override
    public void onResume() {
        super.onResume();
        if(Env.getAppContext().isInitial) {
            runThreadAction("notice");
            runThreadAction("image");
            runThreadAction("getCurrentCourse");
//            runThreadAction("SchoolInfo");
            courseName.setText("正在查询课程...");
            content.setText("正在加载学校通知...");
        }

    }

    @Override
    public void runThreadAction(String actionName) {
        super.runThreadAction(actionName);
    }

    private int CurrentPage = 1;

    @Override
    protected Object runThreadActionExceute(String actionName) {
        super.runThreadActionExceute(actionName);
        if(actionName.equals("notice")){
            return Env.getAppPresenter().getClassInfoList(actionName,1, 10);
        }else if(actionName.matches("[0-9]+")){
            return Env.getAppPresenter().getClassInfoById(actionName);
        }else if(actionName.equals("getCurrentCourse")){
            return Env.getAppPresenter().getCurrentCourse(Env.getAppContext().classId);
        }else if(actionName.equals("image")){
            return Env.getAppPresenter().getClassInfoList(actionName,1, 1);
        }else if(actionName.matches("SchoolInfo")){
            return Env.getAppPresenter().getArcticList(actionName,CurrentPage,Env.getAppContext().itemCount);
        }else {
            return Env.getAppPresenter().getSchoolInfo(actionName);
        }
    }

    private Spanned sp;
    @Override
    protected void runThreadActionSuccess(String actionName, Object result) {
        super.runThreadActionSuccess(actionName, result);
        if(actionName.equals("notice")){
            getClassInfoListResponse response = (getClassInfoListResponse) result;
            if(response.isSuccess()){
                list = response.list;
                if(!list.isEmpty()) runThreadAction(list.get(count).getId());
            }else{
                content.setText(response.getErrMsg());
                ToastUtil.showToast(context,response.getErrMsg());
            }
        }else if(actionName.matches("[0-9]+")) {
            getClassInfoByIdResponse response = (getClassInfoByIdResponse) result;
            if (response.isSuccess()) {
                title.setText(list.get(count).getTitle());
                time.setText(list.get(count).getCreateTimeText());
                final String html = EscapeUnescapeUtil.unescape(response.Detail);
                ThreadPool.getInstance().execute(new Runnable() {
                    @Override
                    public void run() {
                        sp =  Html.fromHtml(html, new Html.ImageGetter() {
                            @Override
                            public Drawable getDrawable(String source) {
                                String s =  source.contains("http") ? source:Env.getAppContext().IP + source;
                                InputStream is = null;
                                try {
                                    is = (InputStream) new URL(s).getContent();
                                    Drawable d = Drawable.createFromStream(is,null);
                                    d.setBounds(0, 0, d.getIntrinsicWidth(),
                                            d.getIntrinsicHeight());
                                    is.close();
                                    return d;
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    return null;
                                }
                            }
                        }, null);

                        mhandler.sendEmptyMessage(2);
                    }
                });

            } else {
                ToastUtil.showToast(context, response.getErrMsg());
                content.setText(response.getErrMsg());

            }
        }else if(actionName.equals("getCurrentCourse")) {
            isFragment = false;
            getCurrentCourseResponse response = (getCurrentCourseResponse) result;
            if(response.isSuccess()){
                teacherName.setText(response.TeacherName);
                currentTime.setText("星期"+response.WeekNo+"第"+response.ClassNo+"节");
                courseName.setText(response.CourseName);
                Glide.with(context).load(Env.getAppContext().IP+"hh").error(R.drawable.img_02).into(image);
            }else{
                if(Env.getAppContext().classId != null){
                    courseName.setText("该时间段无课程");
                }else{
                    courseName.setText(response.getErrMsg());
                }
            }
        }else if(actionName.equals("image")){
            getClassInfoListResponse response = (getClassInfoListResponse) result;
            if(response.isSuccess()){
                if(!response.list.isEmpty()) {
                    strings = response.list.get(0).getStrings();
                    if(!strings.isEmpty()) {
                        Glide.with(context).load(Env.getAppContext().IP + strings.get(currentImageItem)).diskCacheStrategy(DiskCacheStrategy.RESULT)
                                .placeholder(R.drawable.imageload).error(R.drawable.imagefail).into(photo);
                        if(autoPlayImageThread == null) {
                            autoPlayImageThread = new AutoPlayImageThread();
                            autoPlayImageThread.start();
                        }
                    }else {
                        ToastUtil.showToast(context,"班级暂时没有图片");
                    }

                }else{
                    ToastUtil.showToast(context,"班级暂时没有图片");
                }
            }else{
                ToastUtil.showToast(context,response.getErrMsg());

            }
        }else if(actionName.matches("SchoolInfo")) {
            getArcticListResponse response = (getArcticListResponse) result;
            if(!response.list.isEmpty()) {
                for(int i =0 ;i <response.list.size(); i++){
                    runThreadAction(response.list.get(i).getTitle());
                }
            }
        }else {
            getSchoolInfoResponse response = (getSchoolInfoResponse) result;
            if (response.VideoData != null && !response.VideoData.isEmpty()) {
                videoPath.add(response.VideoData.get(0).RealPathName);
                play.setVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    protected void runThreadActionError(String actionName, Exception ex) {
        super.runThreadActionError(actionName, ex);
    }


    @SuppressLint("HandlerLeak")
    private Handler mhandler = new Handler() {
        @SuppressLint("SetTextI18n")
        @Override
        public void handleMessage(final Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case  2:
                    content.setText(sp);
                    break;
                case 3:
                    isFragment = true;
                    runThreadAction("notice");
                    runThreadAction("image");
                    runThreadAction("getCurrentCourse");
                    courseName.setText("正在查询课程...");
                    content.setText("正在加载学校通知...");
                    break;

                case 4:
                    currentImageItem++;
                    if(currentImageItem > strings.size()-1) currentImageItem = 0;
                    Glide.with(context).load(Env.getAppContext().IP + strings.get(currentImageItem))
                            .placeholder(R.drawable.imageload).error(R.drawable.imagefail).into(photo);
                    break;
            }
        }
    };

    private View.OnClickListener leftListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if(count == 0) {
                ToastUtil.showToast(context,"没有上一条了");
                return;
            }
            runThreadAction(list.get(--count).getId());
        }
    };
    private View.OnClickListener rightListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if(count >= list.size()-1) {
                ToastUtil.showToast(context,"没有下一条了");
                return;
            }
            runThreadAction(list.get(++count).getId());
        }
    };
    private View.OnClickListener photoListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if(!strings.isEmpty()) {

                H_ImageDailog = new H_ImageDailog(getActivity(),strings);
                H_ImageDailog.showDialog();
                H_ImageDailog.getCloseView().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        H_ImageDailog.closeDialog();
                    }
                });
            }else{
                ToastUtil.showToast(context,"正在获取班级图片...");
                runThreadAction("image");
            }

        }
    };

    private class getCurrentCourseThread extends Thread {

        private boolean stopFlag = false;
        @Override
        public void run() {
            while (!stopFlag) {
                if(!isFragment) {
                    try {
                        Thread.sleep(1000*60*10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();

                    }
                    mhandler.sendEmptyMessage(3);
                }

            }
        }
        /**
         * 通知线程需要停止
         */
        private void stopRun() {
            stopFlag = true;
        }
    };

    private class AutoPlayImageThread extends Thread {

        private boolean stopFlag = false;
        @Override
        public void run() {
            while (!stopFlag) {
                if(!isFragment) {
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();

                    }
                    mhandler.sendEmptyMessage(4);
                }

            }
        }
        /**
         * 通知线程需要停止
         */
        private void stopRun() {
            stopFlag = true;
        }
    };

}
